
package chapter4;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Ex11 extends JApplet {
  public static void main(String s[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JApplet applet = new Ex11();
    applet.init();
    frame.getContentPane().add(applet);
    frame.pack();
    frame.setVisible(true);
  }
  
  public void init() {
    JPanel panel = new Ex11Panel();
    getContentPane().add(panel);
  }
}

class Ex11Panel extends JPanel implements ActionListener{
    double x0, y0;
    double dx, dy;
    double t;
    int w = 600;
    int h = 400;
    int x;
    int y;
        
    
    public Ex11Panel() {
        setPreferredSize(new Dimension(w+20, h+20));
        x0 = 0;
        y0 = h * Math.random();
        t = 0;
        dy = Math.random();
        dx = Math.sqrt(1-dy*dy);
        
        Timer timer = new Timer(50, this);
        timer.start();
    }

    protected void paintComponent(java.awt.Graphics g) {
        super.paintComponent(g);
        g.translate(10, 10);
        g.setColor(Color.blue);
        g.fillOval(x-10, y-10, 20, 20);
    }    

    public void actionPerformed(ActionEvent actionEvent) {
        t += 5;
        x = (int)(x0 + dx * t);
        y = (int)(y0 + dy * t);
        if (x <= 0 || x >= w) {
            t = 0;
            dx = -dx;
            x0 = x;
            y0 = y;
        }
        if (y <= 0 || y >= h) {
            t = 0;
            dy = -dy;
            x0 = x;
            y0 = y;
        }        
        repaint();
    }    
}
